package cn.zhentao.service.impl;

import cn.zhentao.common.Result;
import cn.zhentao.utils.aliyun.DuXinTest;
import cn.zhentao.utils.common.NicknameGenerator;
import cn.zhentao.dtos.ResponseResult;
import cn.zhentao.enums.AppHttpCodeEnum;
import cn.zhentao.user.dto.LoginDto;
import cn.zhentao.utils.common.AppJwtUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zhentao.user.pojo.TUser;
import cn.zhentao.service.TUserService;
import cn.zhentao.mapper.TUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Random;

/**
* @author EWEWW
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2024-06-26 15:20:12
*/
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService{
   @Autowired
   private TUserMapper tUserMapper;
    //用户登录
   private TUser userinfo=null;

    //验证码
    private String User_regiest_code=null;

    @Override
    public void Code_request(String phone) {
        //验证码接口
        String code = DuXinTest.DuXin(phone);
        System.out.println("真验证码:"+code);
//        String code= String.valueOf(new Random().nextInt(99999));
//        System.out.println("测试的验证码："+code);
        User_regiest_code=code;//验证码
    }



    @Override
    public ResponseResult login(LoginDto dto) {
        //先判断是否为空
        if(StringUtils.isNotBlank(dto.getPhone())){
            //校验用户存不存在
       TUser tUser = tUserMapper.selectOne(Wrappers.<TUser>lambdaQuery().eq(TUser::getPhone, dto.getPhone()));
            //判断是否存在
        if(tUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"账号不存在");
        }
        //验证码登录流程
        if(StringUtils.isNotBlank(dto.getCode())){  //验证码不等于空，说明用户想要用验证码进行登录
            //判断验证码是否正确
            if(dto.getCode().equals(User_regiest_code)){
                //判断该账号是否被禁用
                if(tUser.getStatus()==1){   //1禁用状态
                    return ResponseResult.errorResult(500, "该账户已被封号,请联系管理员");
                }
                userinfo=tUser;
                //登录成功
                String token = AppJwtUtil.getToken(tUser.getId().longValue());
                return ResponseResult.okResult(token);
            }
            return ResponseResult.errorResult(500, "验证码错误");
        }
        //比对密码是否正确
           String salt = tUser.getSalt();
           String pass = dto.getUsername();
        //进行加密
         String password = DigestUtils.md5DigestAsHex((salt + pass).getBytes());
         //比较是否正确
         if(!tUser.getPassword().equals(password)){
             return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码不正确");
         }
         //判断该账号是否被禁用
            if(tUser.getStatus()==1){   //1禁用状态
                return ResponseResult.errorResult(500, "该账户已被封号,请联系管理员");
            }
         //登录成功
            String token = AppJwtUtil.getToken(tUser.getId().longValue());
            userinfo=tUser;
            return ResponseResult.okResult(token);
        }else{//否侧就是游客登录
            String token = AppJwtUtil.getToken(0L);
            return ResponseResult.okResult(token);
        }
    }
    // 登录后的个人信息返回
    @Override
    public TUser info() {
        return userinfo;
    }

    //用户注册
    @Override
    public ResponseResult regiest(TUser tUser) {
        if(StringUtils.isBlank(tUser.getUsername()) || StringUtils.isBlank(tUser.getPhone()) || StringUtils.isBlank(tUser.getCode())){
            return ResponseResult.errorResult(500, "参数不能为空");
        }
        //判断验证码是否正确
        if(!tUser.getCode().equals(User_regiest_code)){
            return ResponseResult.errorResult(500, "验证码错误");
        }
        //判断是否存在
        TUser one = tUserMapper.selectOne(Wrappers.<TUser>lambdaQuery().eq(TUser::getPhone,tUser.getPhone()));

        if(one !=null){
            return ResponseResult.errorResult(500, "账号已存在");
        }
        if(StringUtils.isBlank(tUser.getName())){  //昵称为空  随机名称
            String name = NicknameGenerator.generateRandomNickname();//随机网名
            tUser.setName(name);
        }
        if(StringUtils.isBlank(tUser.getAvatar())){ //默认头像
            tUser.setAvatar("https://img1.baidu.com/it/u=2235480055,3335412585&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=800");
        }
        String salt = String.valueOf(new Random().nextInt(9999));//随机盐
        String password = DigestUtils.md5DigestAsHex((salt + tUser.getUsername()).getBytes());//加密密码
        tUser.setSalt(salt);
        tUser.setPassword(password);
        tUserMapper.insert(tUser);
        return ResponseResult.okResult(200, "注册成功");
    }

    //用户信息完善
    @Override
    public ResponseResult update_user(TUser tUser) {
        if(tUser.getId() == null){
            return ResponseResult.errorResult(500,"修改失败，用户id不能为空");
        }

        if(StringUtils.isNotBlank(tUser.getCode())){  //有验证码说明用户想要修改密码
            if(tUser.getUsername() == null || tUser.getPhone()==null){
                return ResponseResult.errorResult(500,"参数不能为空");
            }
            TUser one = this.getOne(Wrappers.<TUser>lambdaQuery().eq(TUser::getPhone, tUser.getPhone()));
            if(one == null){
                return ResponseResult.errorResult(500,"没有改手机号,请先注册");
            }
            //判断验证码是否正确
            if(!tUser.getCode().equals(User_regiest_code)){
                return ResponseResult.errorResult(500,"验证码错误");
            }
            //根据手机号修改
            String salt = String.valueOf(new Random().nextInt(9999));//随机盐
            String password = DigestUtils.md5DigestAsHex((salt + tUser.getUsername()).getBytes());//加密密码
            tUser.setSalt(salt);
            tUser.setPassword(password);
            this.updateById(tUser);
            TUser newuser = this.getById(tUser.getId());//根据id查询
            return ResponseResult.okResult(newuser);
        }

        //用户选择的卡进行添加对应次数
        if(tUser.getCarId() != null){
            if(tUser.getCarId() == 3){
                tUser.setOrderNum(12);  //svip卡
                tUser.setBalance(300.00);
            }else if(tUser.getCarId() == 2){
                tUser.setOrderNum(8);   //vip卡
                tUser.setBalance(200.00);
            }else if(tUser.getCarId() == 1){
                tUser.setOrderNum(4);  //普通卡
                tUser.setBalance(100.00);
            }
        }
        this.updateById(tUser);//提交到数据库中
        TUser newuser = this.getById(tUser.getId());//根据id查询
        //返回给前端
        return ResponseResult.okResult(newuser);
    }
}




